package com.dfxy.blog.dao;

import com.dfxy.blog.entity.Blog;
import com.mysql.cj.util.StringUtils;

import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.List;

public class BlogDao {

    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static ApproveDao approveDao = new ApproveDao();

    public static String dateTimeFormat(java.util.Date date) {
        return dateTimeFormat.format(date);
    }
    public Blog publish(Connection con, Blog blog) throws SQLException {
        if (con == null || blog == null
                || StringUtils.isEmptyOrWhitespaceOnly(blog.getContent())
        ) {
            return null;
        }

        String sql = "insert into blog " +
                "(username, content, publish_time, approve_count) " +
                "values (?,?,?,?)";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setString(1, blog.getUsername());
        pstat.setString(2, blog.getContent());
        pstat.setString(3, dateTimeFormat.format(blog.getPublishTime()));
        pstat.setInt(4, blog.getApproveCount());

        int update_result = pstat.executeUpdate();
        if (update_result == 0) {
            return null;
        }

        return blog;
    }

    public List<Blog> blogList(Connection con) throws SQLException {
        if (con == null) {
            return null;
        }

        List<Blog> blogList = new ArrayList<>();

        String sql = "select * from blog";
        PreparedStatement pstat = con.prepareStatement(sql);
        ResultSet rs = pstat.executeQuery();

        // head → row1 → row2 → ……
        while(rs.next()) {

            int id = rs.getInt("id");
            String username = rs.getString("username");
            String content = rs.getString("content");
            // Date publishTime = rs.getDate("publish_time");
            Timestamp timestamp = rs.getTimestamp("publish_time");
            int approveCount = rs.getInt("approve_count");

            // 根据blog表中的记录创建Blog对象
            Blog blog = new Blog(
                    id,
                    username,
                    content,
                    new java.util.Date(timestamp.getTime()),
                    approveCount
            );

            blog.setApproveUsernameSet(approveDao.approveUsernameSet(con, blog.getId()));

            // 把blog对象加入到blogList中
            blogList.add(blog);
        }

        blogList.sort(new Comparator<Blog>() {
            @Override
            public int compare(Blog o1, Blog o2) {
                return o2.getPublishTime().compareTo(o1.getPublishTime());
            }
        });

        return blogList;
    }

    public Blog approve(Connection con, Blog blog) throws SQLException {
        if (con == null || blog == null) {
            return null;
        }

        String sql = "select approve_count from blog where id=?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setInt(1, blog.getId());

        ResultSet resultSet = pstat.executeQuery();

        int approveCount = 0;
        if(resultSet.next()) {
            approveCount = resultSet.getInt("approve_count");
        } else {
            return null;
        }
        approveCount++;

        sql = "update blog set approve_count=? where id=?";
        pstat = con.prepareStatement(sql);
        pstat.setInt(1, approveCount);
        pstat.setInt(2, blog.getId());

        int updateResult = pstat.executeUpdate();
        blog.setApproveCount(approveCount);
        if (updateResult > 0) {
            return blog;
        } else {
            return null;
        }
    }

    public Blog refreshApproveCount(Connection con, Blog blog) throws SQLException {
        if (con == null || blog == null) {
            return null;
        }

        String sql = "select count(distinct approve_username) as approve_count" +
                " from approve where blog_id = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setInt(1, blog.getId());
        ResultSet queryResult = pstat.executeQuery();

        int approveCount = 0;
        if (queryResult.next()) {
            approveCount = queryResult.getInt("approve_count");
        }

        blog.setApproveCount(approveCount);

        // 更新blog表中的点赞数
        sql = "update blog set approve_count = ? where id = ?";
        pstat = con.prepareStatement(sql);
        pstat.setInt(1, blog.getApproveCount());
        pstat.setInt(2, blog.getId());
        pstat.executeUpdate();

        return blog;
    }

    public Blog delete(Connection con, Blog blog) throws SQLException {
        if (con == null || blog == null) {
            return null;
        }

        String sql = "delete from blog where id = ?";
        PreparedStatement pstat = con.prepareStatement(sql);
        pstat.setInt(1, blog.getId());

        int updateResult = pstat.executeUpdate();

        if (updateResult > 0) {
            return blog;
        } else {
            return null;
        }
    }
}
